<?php

namespace app\admin\model\facrm;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Business extends Model
{

    use SoftDelete;
    // 表名
    protected $name = 'facrm_business';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
	protected static function init()
	{
		$forfun = function (&$row) {
			foreach ($row->data as $k => $v) {
				//数组的字段处理成字符串,主要处理是自定义字段多选的值
				if (!empty($v) && is_array($v)) $row->data[$k] = implode(',', $v);
			}
		};
		/**
		 * 插入前
		 */
		self::beforeInsert(function ($row) use ($forfun) {
			$forfun($row);
		});
		/**
		 * 更新前
		 */
		self::beforeUpdate(function ($row) use ($forfun) {
			$forfun($row);
		});
	}
    /**
     * 获取商机状态
     * @return string[]
     */
    public function getIsEndList(){
        return ['0'=>"洽淡中",'1'=>"成交",'2'=>"失败",'3'=>"无效"];
    }
    /**
     * 创建者
     */
    public function createUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'create_user_id');
    }
    /**
     * 拥有者
     */
    public function ownerUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'owner_user_id');
    }
    /**
     * 客户对象
     * @return \think\model\relation\BelongsTo
     */
    public function customer(){
        return $this->belongsTo('\app\admin\model\facrm\Customer', 'customer_id', 'id');
    }

    /**
     * 关联商品
     * @return \think\model\relation\HasMany
     */
    public function product()
    {
        return $this->hasMany('\app\admin\model\facrm\business\Product','business_id','id');
    }

    /**
     * 趋势Echart
     * @return bool
     */
    public function getEchartData($startDate,$endDate,$owner_user_ids)
    {

        $thisModel = $this;
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);
        $isnotrangeDate = empty($starttime) && empty($endtime);


        $nearly = '30';
        if ($isnotrangeDate) {
            $endtime = time();
            $nearly -= 1;
            $starttime = strtotime("-{$nearly} day");  // 最近30天日期
        } elseif ($starttime > $endtime) {
            $this->error = __('起始时间要小于终止时间');
            return false;
        }
        $totalseconds = $endtime - $starttime;;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }
        //增量

        if ($owner_user_ids) {
            $thisModel->where('owner_user_id','in', $owner_user_ids);
        }
        $lists = $thisModel->where('create_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(create_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();



        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }


        $c_count = $d_count = array_fill_keys($column, 0);

        foreach ($lists as $k => $v) {
            $c_count[$v['add_date']] = $v['nums'];//客户增量
        }


        $result = [
            'date' => array_keys($c_count),
            'c_count' => array_values($c_count),
        ];

        $data = [
            'date' => $result['date'],
            'data' => [
                __("新增商机") => $result['c_count'],
            ],
        ];
        return $data;

    }


}